# pylint: disable-msg=E1101
"""
@author: Sergiy Tsymbalyuk
"""

import logging

from pylons import tmpl_context as c, request, url
from pylons.i18n import lazy_ugettext as _
from pylons.controllers.util import redirect

from repoze.what.plugins.pylonshq import ControllerProtector
from repoze.what.predicates import not_anonymous

from chowa.lib.base import BaseController, render, Session
from chowa.lib.site.navigation import Tab
from chowa.lib.site.forms import TabularFieldSet, password_length, password_ascii, password_alphanum
from chowa.model.site import Message, Receipt
from chowa.model.auth import User

log = logging.getLogger(__name__)

@ControllerProtector(not_anonymous())
class ProfileController(BaseController):
    def __before__(self):
        self.user = request.environ.get('repoze.who.identity')['user']
        c.main_heading = self.user
    
    def index(self):
        query = Session.query(Receipt).filter_by(is_read=False)
        c.messages = query.filter_by(recipient_id=self.user.id).count()
        c.user = self.user
        return render('/social/profile/index.html')
    
    def messages(self):
        query = Session.query(Receipt)
        c.receipts = query.filter_by(recipient_id=self.user.id).all()
        return render('/social/profile/messages.html')
    
    def preferences(self):
        fs = TabularFieldSet(self.user)
        fs.configure(include=[fs.theme])
        if request.method == 'POST':
            fs.rebind(data=request.POST)
            fs.sync()
            Session.commit()
        c.form = fs.render()
        return render('/social/profile/preferences.html')
    
    def password(self):
        user = Session.query(User).get(self.user.id)
        fs = TabularFieldSet(user)
        include = [fs._password.validate(password_length(6)) \
                               .validate(password_ascii) \
                               .validate(password_alphanum),
                   fs.repeat_password]
        fs.configure(include=include)
        if request.method == 'POST':
            fs.rebind(data=request.POST)
            if fs.validate():
                fs.sync()
                user.bad_password = False
                Session.commit()
                return redirect(url.current(action='index'))
        c.form = fs.render()
        return render('/social/profile/password.html')
